package com.sushi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sushi.exception.BusinessException;
import com.sushi.repository.entity.UserEntity;
import com.sushi.repository.mapper.UserMapper;
import com.sushi.request.UserPageReq;
import com.sushi.request.UserReq;
import com.sushi.response.ResponseBO;
import com.sushi.response.ResponsePageBO;
import com.sushi.response.UserResp;
import com.sushi.service.UserService;
import com.sushi.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 服务实现类
 * @date 2023-05-02
 * @time 17:16:19
 * @author Administrator
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private UserMapper userMapper;

    

    /**
     * 新增
     */
    @Override
    public ResponseBO<UserResp> add(UserReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        UserEntity entity = BeanUtil.convert(req, UserEntity.class);
        if (ObjectUtil.isEmpty(entity)) {
            throw new BusinessException("保存失败");
        }
        checkSignUp(req);
        entity.insert();
        return ResponseUtil.ok(BeanUtil.convert(entity, UserResp.class));
    }
    private void checkSignUp(UserReq req) {
        if (StringUtil.isBlank(req.getAccount())) {
            throw new BusinessException("账号不能为空");
        }
        if (StringUtil.isBlank(req.getPassword())) {
            throw new BusinessException("密码不能为空");
        }
        List<UserEntity> existList = list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getDeleted, 0L).eq(UserEntity::getAccount, req.getAccount()));
        if (CollectionUtil.isNotEmpty(existList)) {
            throw new BusinessException("账号用户已存在，请换一个账号名");
        }
    }

    @Override
    public ResponseBO<String> checkAccount(UserReq req) {
        String result = "账号验证通过";
        List<UserEntity> existList = list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getDeleted, 0L).eq(UserEntity::getAccount, req.getAccount()));
        if (CollectionUtil.isNotEmpty(existList)) {
            result = "账号用户已存在，请换一个账号名";
        }
        return ResponseUtil.ok(result);
    }

    /**
     * 逻辑删除
     */
    @Override
    public ResponseBO<UserResp> logicRemove(UserReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        if (StringUtil.isBlank(req.getId())) {
            throw new BusinessException("id不能为空");
        }
        UserEntity entity = getById(req.getId());
        removeById(req.getId());
        return ResponseUtil.ok(BeanUtil.convert(entity, UserResp.class));
    }

    /**
     * 更新
     */
    @Override
    public ResponseBO<UserResp> updateByField(UserReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getId())) {
            throw new BusinessException("必要参数不能为空");
        }
        UserEntity entity = getById(req.getId());
        if (ObjectUtil.isEmpty(entity)) {
            return ResponseUtil.error("信息不存在，无法更新");
        }
        if (StringUtil.isNotBlank(req.getUserName())) {
            entity.setUserName(req.getUserName());
        }
        if (StringUtil.isNotBlank(req.getPassword())) {
            entity.setPassword(req.getPassword());
        }
        if (StringUtil.isNotBlank(req.getUserGender())) {
            entity.setUserGender(req.getUserGender());
        }
        if (ObjectUtil.isNotEmpty(req.getCredit())) {
            entity.setCredit(req.getCredit());
        }
        if (StringUtil.isNotBlank(req.getRealName())) {
            entity.setRealName(req.getRealName());
        }
        if (StringUtil.isNotBlank(req.getIdentityNum())) {
            entity.setIdentityNum(req.getIdentityNum());
        }
        if (StringUtil.isNotBlank(req.getEmail())) {
            entity.setEmail(req.getEmail());
        }
        if (StringUtil.isNotBlank(req.getPhone())) {
            entity.setPhone(req.getPhone());
        }
        if (ObjectUtil.isNotEmpty(req.getAmount())) {
            entity.setAmount(req.getAmount());
        }
        if (StringUtil.isNotBlank(req.getStatus())) {
            entity.setStatus(req.getStatus());
        }

        entity.updateById();
        log.info("更新成功：{}", JSON.toJSONString(entity));
        return ResponseUtil.ok(BeanUtil.convert(entity, UserResp.class));
    }

    /**
     * 列表
     */
    @Override
    public ResponsePageBO<UserResp> listByCondition(UserPageReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        if (ObjectUtil.isEmpty(req) || ObjectUtil.isEmpty(req.getPageNum()) || ObjectUtil.isEmpty(req.getPageSize())) {
            throw new BusinessException("必要参数不能为空");
        }
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getDeleted, 0L);

        wrapper.eq(StringUtil.isNotBlank(req.getId()), UserEntity::getId, req.getId());
        wrapper.like(StringUtil.isNotBlank(req.getUserName()), UserEntity::getUserName, req.getUserName());
        wrapper.eq(StringUtil.isNotBlank(req.getUserGender()), UserEntity::getUserGender, req.getUserGender());
        wrapper.eq(StringUtil.isNotBlank(req.getIdentity()), UserEntity::getIdentity, req.getIdentity());
        wrapper.eq(StringUtil.isNotBlank(req.getStatus()), UserEntity::getStatus, req.getStatus());

        wrapper.orderByDesc(UserEntity::getGmtCreateTime);

        String searchContent = req.getSearchContent();
        if (StringUtil.isNotBlank(searchContent)) {
            wrapper.and(wra -> wra.or(e -> e.like(UserEntity::getAccount, searchContent))
                    .or(e -> e.like(UserEntity::getRealName, searchContent))
                    .or(e -> e.like(UserEntity::getEmail, searchContent))
                    .or(e -> e.like(UserEntity::getPhone, searchContent))
            );
        }

        if (ObjectUtil.isNotEmpty(req.getStartTime())) {
            wrapper.ge(UserEntity::getGmtCreateTime, req.getStartTime());
        }
        if (ObjectUtil.isNotEmpty(req.getEndTime())) {
            wrapper.le(UserEntity::getGmtCreateTime, req.getEndTime());
        }

        Page<UserEntity> page = page(new Page<>(req.getPageNum(), req.getPageSize()), wrapper);
        if (ObjectUtil.isEmpty(page) || CollectionUtil.isEmpty(page.getRecords())) {
            return ResponsePageUtil.ok(req, new ArrayList<>(), 0L);
        }
        List<UserResp> convert = BeanUtil.convert(page.getRecords(), UserResp.class);
        return ResponsePageUtil.ok(req, convert, page.getTotal());
    }

    /**
     * 详情
     */
    @Override
    public ResponseBO<UserResp> detail(UserReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getId())) {
            throw new BusinessException("必要参数不能为空");
        }
        UserEntity entity = getById(req.getId());
        if (ObjectUtil.isEmpty(entity)) {
            throw new BusinessException("对象不存在");
        }
        return ResponseUtil.ok(BeanUtil.convert(entity, UserResp.class));
    }

    @Override
    public ResponseBO<String> signUp(UserReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getAccount()) || StringUtil.isBlank(req.getPassword())) {
            return ResponseUtil.error("必要信息不能为空");
        }
        if (StringUtil.isNotBlank(req.getIdentity()) && StringUtil.equals(req.getIdentity(), "1")) {
            if (StringUtil.isBlank(req.getRealName()) || StringUtil.isBlank(req.getIdentityNum())) {
                return ResponseUtil.error("真实信息不能为空");
            }
        }
        UserEntity user = BeanUtil.convert(req, UserEntity.class);
        save(user);
        log.info("新建用户：{}", JSON.toJSONString(user));
        return ResponseUtil.ok("注册成功，请登录");
    }

    @Override
    public ResponseBO<UserResp> login(UserReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        System.out.println(req.getAccount());
        System.out.println(req.getIdentity());
        System.out.println(req.getPassword());
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getAccount()) || StringUtil.isBlank(req.getPassword()) || StringUtil.isBlank(req.getIdentity())) {
            throw new BusinessException("登录信息不能为空");
        }
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getAccount, req.getAccount()).eq(UserEntity::getStatus, 1L).eq(UserEntity::getDeleted, 0L).eq(UserEntity::getIdentity, req.getIdentity());
        List<UserEntity> list = list(wrapper);
        System.out.println(list);
        UserEntity user = getOne(wrapper);
        if (ObjectUtil.isEmpty(user)) {
            throw new BusinessException("用户不存在");
        }
        if (StringUtil.equals(req.getPassword(), user.getPassword())) {
            UserResp convert = BeanUtil.convert(user, UserResp.class);
            return ResponseUtil.ok(convert);
        }
        throw new BusinessException("密码错误");
    }




    private UserEntity getIdentity(String userId) {
        return getById(userId);
    }


}